package com.ks.core.base;


import cn.hutool.core.date.DateTime;
import com.ks.core.util.MD5Util;

import java.time.DateTimeException;

/**
 * Created by WangLiCheng:nomad21st@163.com:KingDee Co. on 2020/12/20.
 * 这个对像是对应于api中httpHeader内携带的信息的。它通过在刚进入Api时从header中获取的相关
 * 携带的数据，实现在后续的service层的操作中，可以随时获取一些基础数据。
 * 我们定义在HttpHeader中存放的Token信息的数据结构是：TenantID:OrgID:OrgSubID:UserID:TimeStamp:Session
 * Session是TenantID:OrgID:OrgSubID:UserID:TimeStamp 作为字符串进行MD5加密的密文
 */
public class OperationContext {
    private Long tenantId=0L;
    private Long orgId=0L;
    private Long orgSubId=0L;
    private Long userId=0L;
    private Long timeStamp=0L;
    private String session="";
    private boolean isVerification=false;
    private String token="";

    public static OperationContext create(String token) {
        if (Validator.isNullOrEmpty(token)) {
            return new OperationContext(CreateDefaultToken());
        }else{
            return new OperationContext(token);
        }
    }

    private static String CreateDefaultToken(){
        return "0:0:0:0:0:"+ MD5Util.md5("0:0:0:0:0");
    }

    private OperationContext(String httpHeaderTokenString) {
        this.token =Validator.isNullOrEmpty(httpHeaderTokenString)?CreateDefaultToken():httpHeaderTokenString;
        String[] items=token.split(":");
        if(items.length>5) {
            this.tenantId = Long.parseLong(items[0]);
            this.orgId = Long.parseLong(items[1]);
            this.orgSubId = Long.parseLong(items[2]);
            this.userId = Long.parseLong(items[3]);
            this.timeStamp = Long.parseLong(items[4]);
            this.session = items[5];
            this.isVerification = items[5].contentEquals(MD5Util.md5(items[0]+":"+items[1]+":"+items[2]+":"+items[3]+":"+items[4]));
        }else{
            this.isVerification=false;
            this.session = "0";
        }
    }
    public Long getOrgId() {
        return orgId;
    }

    public Long getUserId() {
        return userId;
    }

    public Long getTenantId(){
        return tenantId;
    }
    public Long getOrgSubId(){
        return orgSubId;
    }
    public Long getTimeStamp(){
        return timeStamp;
    }
    public String getSession(){
        return session;
    }
    public boolean isVerification(){
        return isVerification;
    }
    public DateTime getTime(){
        return new DateTime(timeStamp);
    }
    public String getToken(){
        return token;
    }


//    public static void main(String[] args) throws Exception {
//        String s = "20000:30000:40000:500000000000000:"+ MD5Util.md5("10000:20000:30000:40000:500000000000000");
//        System.out.println("原始：" + s);
//        OperationContext opContext = OperationContext.create(s);
//        System.out.println("对像：" + opContext.getSession() + ":"+opContext.getTime() + ":"+opContext.isVerification());
//    }

}

